package com.xinke.module.system.service.user;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.xinke.module.system.model.vo.user.*;
import com.xinke.module.system.model.entity.user.UserRoleDO;
import com.xinke.component.common.pojo.PageResult;
import com.xinke.component.common.pojo.PageParam;
import com.xinke.component.common.util.object.BeanUtils;

import com.xinke.module.system.mapper.user.UserRoleMapper;

import static com.xinke.component.common.exception.util.ServiceExceptionUtil.exception;
import static com.xinke.module.system.enums.ErrorCodeConstants.*;

/**
 * 用户和角色关联 Service 实现类
 *
 * @author yzx
 */
@Service
@Validated
public class UserRoleServiceImpl implements UserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public Long createUserRole(UserRoleSaveReqVO createReqVO) {
        // 插入
        UserRoleDO userRole = BeanUtils.toBean(createReqVO, UserRoleDO.class);
        userRoleMapper.insert(userRole);
        // 返回
        return userRole.getUserRoleId();
    }

    @Override
    public void updateUserRole(UserRoleSaveReqVO updateReqVO) {
        // 校验存在
        validateUserRoleExists(updateReqVO.getUserRoleId());
        // 更新
        UserRoleDO updateObj = BeanUtils.toBean(updateReqVO, UserRoleDO.class);
        userRoleMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserRole(Long userRoleId) {
        // 校验存在
        validateUserRoleExists(userRoleId);
        // 删除
        userRoleMapper.deleteById(userRoleId);
    }

    private void validateUserRoleExists(Long userRoleId) {
        if (userRoleMapper.selectById(userRoleId) == null) {
            throw exception(null);
        }
    }

    @Override
    public UserRoleDO getUserRole(Long userRoleId) {
        return userRoleMapper.selectById(userRoleId);
    }

    @Override
    public PageResult<UserRoleDO> getUserRolePage(UserRolePageReqVO pageReqVO) {
        return userRoleMapper.selectPage(pageReqVO);
    }

}